﻿using AsmShaderConverter.AsmShader;
using AsmShaderConverter.HlslShader;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AsmShaderConverter.AsmFunctions
{
    public class AsmFunctionTexldp : IConvertToHlsl
    {
        readonly string originalLineOfCode;
        private Register destination;
        private Register coordinates;
        private Register sampler;
        public Register GetDestinationRegister()
        {
            return this.destination;
        }

        public AsmFunctionTexldp(string lineOfCode)
        {
            this.originalLineOfCode = lineOfCode;
            lineOfCode = lineOfCode.Replace(",", ""); // Remove commas.
            lineOfCode = lineOfCode.Trim(); // Remove dead space.
            var values = lineOfCode.Split(' '); // split

            switch (values.Length)
            {
                case 4:
                    this.destination = new Register(values[1], Swizzle.StandardXYZW);
                    this.coordinates = new Register(values[2], Swizzle.StandardXYZW);
                    this.sampler = new Register(values[3], Swizzle.StandardXYZW);
                    break;
                default:
                    throw new Exception("Function can´t be converted! " + lineOfCode);
            }
        }

        public string ToHLSL(AsmShaderFile asmShader)
        {
            if (coordinates.swizzle.Length == 0)
                coordinates.swizzle = new char[] { 'x', 'y', 'z', 'w' };

            string textureName = string.Empty;
            Sampler2Texture sampler;
            if (asmShader.GetSamplerToTextureName(this.sampler.OriginalRegisterName, out sampler))
                textureName = sampler.textureName;
            else
                textureName = "noneRegistered";


            // DX9 style: return String.Format("{0} = tex2Dproj({1}, {2});", this.destination.ToHLSL(), this.sampler.RegisterName, this.coordinates.ToHLSL());
            return String.Format("{0} = {1}.Sample({2}, {3} / {4});", this.destination.ToHLSL(asmShader), textureName, this.sampler.GetRegisterName(asmShader), this.coordinates.GetNameWithNewSwizzle("xy", asmShader), this.coordinates.GetNameWithNewSwizzle("w", asmShader));
        }


        public string ToHLSLWitchComment(AsmShaderFile asmShader)
        {
            return this.ToHLSL(asmShader) + "//" + this.originalLineOfCode;
        }
    }
}
